<template>
	<d2-container>
	<div class="form-area">
		<el-form ref="addForm" :model="addForm" :rules="rules" label-width="90px">
			<div class="form-title">
				<h3>基本信息</h3>
			</div>
			<el-row :gutter="20" style="width: 80%;">
				<el-col :span="12">
					<el-form-item label="调拨原因" prop="applyReason">
						<el-input v-model="addForm.applyReason" placeholder="请输入调拨原因"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="调拨单编号">
						<el-input placeholder="保存系统自动创建" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20" style="width: 80%;">
				<el-col :span="12">
					<el-form-item label="调出仓库" prop="repositoryNameOut">
						<el-select v-model="addForm.repositoryNameOut" placeholder="请选择仓库"
						@change="selectRepositoryOut()" style="width: 100%;">
							<el-option
									v-for="item in repositorys"
									:key="item.id"
									:label="item.repositoryName"
									:value="`${item.id}|${item.repositoryName}|${item.stockType}|${item.shopId}`">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="调入仓库" prop="repositoryNameIn">
						<el-select v-model="addForm.repositoryNameIn" placeholder="请选择仓库"
						@change="selectRepositoryIn()" style="width: 100%;">
							<el-option
									v-for="item in repositorys"
									:key="item.id"
									:label="item.repositoryName"
									:value="`${item.id}|${item.repositoryName}|${item.stockType}|${item.shopId}`">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20" style="width: 80%;">
				<el-col :span="12">
					<el-form-item label="调拨日期" prop="applyDate">
						<el-date-picker
							v-model="addForm.applyDate"
							type="date"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							align="right"
							style="width: 100%;"
							></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="调拨状态" prop="allocationStatus">
						<el-select v-model="addForm.allocationStatus" disabled style="width: 100%;">
							<el-option value="0" label="未处理"></el-option>
							<el-option value="1" label="已确定"></el-option>
							<el-option value="2" label="已撤销"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20" style="width: 80%;">
				<el-col :span="24">
					<el-form-item label="备注" prop="remark">
						<el-input type="textarea" :rows="2" v-model="addForm.remark" placeholder="请输入备注" ></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<div class="form-title">
				<h3>调拨商品信息</h3>
			</div>

			<div class="order-sku-list">
				<div style="align-items:center; display: flex; padding-bottom: 20px;">
					<el-button type="primary" class="form-cancle-btn" @click="showDialog">添加调拨商品</el-button>
					<span style="margin-left: 20px;">选择调出仓库后，仅可选择该仓库下的商品进行调拔。</span>
				</div>

				<el-table :data="detailTableData" stripe border style="width: 100%" >
					    <el-table-column type="index" fixed label="序号" width="50"></el-table-column>
						<el-table-column label="商品名称" prop="productName" width="200"></el-table-column>
						<el-table-column label="商品编码" prop="productCode" width="200"></el-table-column>
						<el-table-column label="SKU名称" prop="productSkuName" width="200"></el-table-column>
						<el-table-column label="SKU编码" prop="productSkuCode" width="200"></el-table-column>
						<el-table-column label="商品条码" prop="productBarCode" width="200"></el-table-column>
						<el-table-column label="可用库存数量" prop="stockQuantity" width="200">
							<template slot="header">
								<span>可用库存数量</span>
								<el-button type="success" icon="el-icon-check" size="mini" plain @click="freshData()">刷新</el-button>
							</template>
						</el-table-column>
						<el-table-column label="单位" prop="unitName" ></el-table-column>
						<el-table-column label="调拨数量" prop="allocationQuantity" width="200">
							<template slot-scope="scope">
								<el-input-number v-model="scope.row.allocationQuantity" size="small" placeholder="请输入数量"
								 :min="0" :max="scope.row.quantity" style="width:100%">
								</el-input-number>
							</template>
						</el-table-column>
				</el-table>
			</div>
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item>
						<div class="form-submit">
						<el-button @click="saveAllocation('addForm',0)" class="form-submit-btn" type="primary">保存</el-button>
						<el-button @click="saveAllocation('addForm',1)" class="form-submit-btn" type="primary">保存并提交</el-button>
						<el-button class="form-cancle-btn" @click="closePage">取消</el-button>
						</div>
					</el-form-item>

				</el-col>
			</el-row>
		</el-form>

		<el-dialog title="调拨商品" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
			<el-table :data="productTableData" stripe border style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column label="商品名称" prop="productName" width="250"></el-table-column>
				<el-table-column label="商品编码" prop="productCode" width="200"></el-table-column>
				<el-table-column label="SKU名称" prop="productSkuName" width="250"></el-table-column>
				<el-table-column label="SKU编码" prop="productSkuCode" width="200"></el-table-column>
				<el-table-column label="商品条码" prop="productBarCode" width="200"></el-table-column>
				<el-table-column label="库存数量" prop="stockQuantity" ></el-table-column>
				<el-table-column label="单位" prop="unitName" ></el-table-column>
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmSelectProduct">确 定</el-button>
			</span>
		</el-dialog>
	</div>
	</d2-container>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { saveOrUpdateAllocationOrder, queryStockProducts } from '@api/allocation/allocation'
import { findAllList } from '@api/repository/repositoryInfo'
export default {
  data () {
    return {
	  repositorys: [],
	  dialogVisible: false,
	  addForm: {
        applyReason: null,
        shopIdOut: null,
        repositoryIdOut: null,
        repositoryNameOut: null,
        stockTypeOut: null,
        shopIdIn: null,
        repositoryIdIn: null,
        repositoryNameIn: null,
        stockTypeIn: null,
        remark: null,
        applyDate: null,
        allocationStatus: '0',
        auditStatus: 0,
        allocationOrderDetails: []
	  },
	  multipleSelection: [],
	  detailTableData: [],
	  productTableData: [],
	  // 表单验证规则
      rules: {
        applyReason: [{ required: true, message: '请输入调拨原因', trigger: 'blur' }],
        repositoryNameOut: [{ required: true, message: '请选择调出仓库', trigger: 'blur' }],
        repositoryNameIn: [{ required: true, message: '请选择调入仓库', trigger: 'blur' }],
        applyDate: [{ required: true, message: '请选择调拨日期', trigger: 'blur' }],
        productTableData: [{ required: true, message: '请添加调拨商品', trigger: 'change' }]
      }

    }
  },
  computed: {
	  ...mapState('d2admin/page', ['opened', 'current']) // 用户获取当前页面的地址，用于关闭
  },
  mounted () {
    this.findRepositorys()
  },
  methods: {
    ...mapActions('d2admin/page', ['close']),
    findRepositorys () {
      findAllList().then((res) => {
        this.repositorys = res.data
      }).catch((err) => {
        console.log('err', err)
        this.loading = false
      })
    },
    closePage () { // 关闭当前窗口
	  let tagName = this.current
	  this.close({ tagName })
    },
    selectRepositoryOut () {
      if (this.addForm.repositoryNameOut) {
        const [key, lable, stockType, shopId] = this.addForm.repositoryNameOut.split('|')
        this.addForm.repositoryIdOut = key
        this.addForm.repositoryNameOut = lable
        this.addForm.stockTypeOut = stockType
        this.addForm.shopIdOut = shopId
      }
    },
    selectRepositoryIn () {
      if (this.addForm.repositoryNameIn) {
        const [key, lable, stockType, shopId] = this.addForm.repositoryNameIn.split('|')
        this.addForm.repositoryIdIn = key
        this.addForm.repositoryNameIn = lable
        this.addForm.stockTypeIn = stockType
        this.addForm.shopIdIn = shopId
      }
    },
    saveAllocation (formName, type) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 调出仓库和调入仓库不能同为一个仓库
          if (this.addForm.repositoryIdOut == this.addForm.repositoryIdIn) {
			 this.$message({
              message: '调出仓库和调入仓库不能同为一个仓库',
              type: 'warning'
            })
			 return
		    }

          this.addForm.auditStatus = type
          if (this.detailTableData.length < 1) {
            this.$message({
              message: '请先选择调拨商品',
              type: 'warning'
            })
            return
          }

          let isFlag = false
          this.detailTableData.forEach(item => {
            if (item.allocationQuantity == undefined || item.allocationQuantity == 0) {
              isFlag = true
            }
          })
          if (isFlag) {
            this.$message({
              message: '调拨数量必须大于0',
              type: 'warning'
            })
            return
          }

          // console.log(JSON.stringify(this.detailTableData))
          this.addForm.allocationOrderDetails = this.detailTableData
          // console.log(JSON.stringify(this.addForm))

          saveOrUpdateAllocationOrder(this.addForm).then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
			    this.closePage()
            } else {
              this.$message({ message: res.message, type: 'error' })
              return
            }
            this.loading = false
          }).catch(err => {
            console.log('err', err)
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    showDialog () {
      if (this.addForm.repositoryIdOut == null) {
        this.$message({
          message: '请选择调出仓库',
          type: 'warning'
        })
        return
      }
      this.dialogVisible = true
      queryStockProducts({ repositoryId: this.addForm.repositoryIdOut }).then(res => {
        this.productTableData = res.data
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
      this.dialogVisible = true
    },
    freshData () {
      if (this.detailTableData.length > 0) {
        queryStockProducts({ repositoryId: this.addForm.repositoryIdOut }).then(res => {
          let list = res.data
          this.detailTableData.forEach(item => {
            list.forEach(item2 => {
              if (item2.stockId == item.stockId) {
                item.stockQuantity = item2.stockQuantity
              }
            })
          })
          this.loading = false
        })
      }
    },

    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    confirmSelectProduct () {
      this.multipleSelection.forEach(item => {
        if (!this.checkItem(item)) {
          this.detailTableData.push(item)
        }
      })
      this.dialogVisible = false
    },
    checkItem (item) {
      let check = false
      this.detailTableData.forEach(item2 => {
        if (item.stockId == item2.stockId) {
          check = true
        }
      })
      return check
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        }).catch(_ => {})
    }
  },
  created () {

  }
}
</script>

<style lang="scss" scoped>
.order-details {
	padding: 20px;
	.order-number {
		width: 100%;
		height: 60px;
		align-items: center;
		display: flex;
		border:#666 1px
		span {
			font-size: 14px;
			color: #333;
			margin: 30px 30px 30px 30px;
		}
	}

	.order-progress {
		width: 100%;
		align-items: center;
		display: flex;
		padding: 50px 0;
		.order-status {
			width: 250px;
			text-align: center;
			flex: 0 0 100px;
			h3 {
				font-size: 24px;
				color: #333;
			}
			p {
				font-size: 14px;
				color: #999;
				margin-top: 10px;
			}
		}
		.order-progress-bar {
			flex: 1 1 auto;
		}
	}

	.order-details-info {
		width: 100%;
		.table-list {
			p {
				font-size: 14px;
				color: #666;
				margin: 3px 0;
			}
		}
	}

	.order-sku-list {
		width: 100%;
		margin-top: 30px;
		.sku-info {
			width: 100%;
			display: flex;
			.sku-image {
				width: 80px;
				height: 80px;
				flex: 0 0 80px;
			}
			.sku-details {
				flex: 1 1 auto;
				h3 {
					font-size: 14px;
					color: #333;
					padding-left: 30px;
				}
				p {
					font-size: 14px;
					color: #999;
					margin-top: 4px;
					padding-left: 30px;
				}
			}
		}
		.sku-summary {
			border: #ebeef5 1px solid;
			border-top: none;
			justify-content: flex-end;
			display: flex;
			padding: 20px;
			.sku-summary-content {
				width: 240px;
				p {
					width: 100%;
					font-size: 14px;
					color: #333;
					justify-content: space-between;
					display: flex;
					margin: 5px 0;
				}
				span {
					font-size: 14px;
				}
				span.sku-summary-text {
					font-size: 18px;
					font-weight: bold;
					color: #ff5642;
				}
			}
		}
	}
}

::v-deep .el-table thead.is-group th {
	background: #fff!important;
}
.warning-text {
	color: #ff5642;
}
.success-text {
	color: #1aa57b;
}
</style>
